package com.zx.cloud.order.api.feign.interceptor;


import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;


/**
 * Feign请求拦截器（设置请求头，传递请求参数）
 * @author zhaoxuan
 * @date 2021-12-23 13:44
 **/
@Component
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        log.info("全局事务xid：{}",RootContext.getXID());
        HttpServletRequest request = getRequest();
        if (request==null){
            return;
        }
        Map<String, String> headers = getHeaders(request);
        headers.forEach(requestTemplate::header);
        log.info("headers:{}",requestTemplate.headers());
    }

    private HttpServletRequest getRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes==null){
           return null;
        }
        return requestAttributes.getRequest();
    }

    private Map<String,String> getHeaders(HttpServletRequest request){
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        while (headerNames!=null&&headerNames.hasMoreElements()){
            String key = headerNames.nextElement();
            String value= request.getHeader(key);
            headers.put(key,value);
        }
        return headers;
    }


}
